package com.example.user

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.LoginEntity
import com.example.base.mvi.BaseActivity
import com.example.base.mvi.HttpType
import com.example.base.mvi.UiState
import com.example.user.databinding.ActivityLoginBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = "/user/LoginActivity")
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding,UserIntent,UserViewModel>() {
    override fun getLayout(): Int  = R.layout.activity_login

    override fun getVM(): Class<UserViewModel> = UserViewModel::class.java

    override fun initView() {
        //点击登录按钮
        binding.btnLogin.setOnClickListener {
            viewModel.sendIntent(UserIntent.login(binding.etPassword.text.toString(),binding.etUsername.text.toString()))
        }
    }

    override fun initData() {
        lifecycleScope.launch {
            viewModel.uiState.collect{
                when(it){

                    is UiState.onSuccess<*> -> {
                        when(it.type){
                            HttpType.DEFAULT -> {
                                ToastUtils.showLong("登录成功")
                                val entity = it.data as LoginEntity

                                SPUtils.getInstance().apply {
                                    put("token",entity.token)
                                    put("uid",entity.id)
                                    put("username",entity.username)
                                    put("role",entity.roleid)
                                }
                                viewModel.sendIntent(UserIntent.roomAdd(entity))

                                //权限控制
                                if(SPUtils.getInstance().getInt("role")==20){
                                    ARouter.getInstance().build("/app/MainActivity").navigation()
                                }else{
                                    ARouter.getInstance().build("/user/ShopActivity").navigation()
                                }
                            }
                           else->{}
                        }


                    }
                    else->{}
                }
            }
        }
    }

}